package com.flashflexpro.flexdirector.adapter.codec {
import com.flashflexpro.flexdirector.adapter.descriptor.DescPropertyAuto;
import com.flashflexpro.flexdirector.model.CodeStringValue;

import mx.automation.Automation;
import mx.automation.AutomationIDPart;
import mx.automation.IAutomationObject;

public class CodecAutoObj extends CodecDefault  implements ICodec{

    override public function encode(obj:Object,
                                    descProperty:DescPropertyAuto, relativeParent:IAutomationObject ):CodeStringValue{
        var rt:CodeStringValue = new CodeStringValue();
        rt.desc = descProperty.getDto();
        var val:Object = getMemberFromObject(obj, descProperty);
        var atName:String;
        if ( val is IAutomationObject) {
            atName = Automation.automationManager.createIDPart( val as IAutomationObject).automationName;
        }
        if( val == null ){
            rt.code = "null";
        }
        else{
            rt.code = "\"" + atName + "\"";
        }
        rt.value = rt.string = atName;
        return rt;
    }

    override public function decode(
            obj:Object,
            value:Object,
            descProperty:DescPropertyAuto,
            relativeParent:IAutomationObject, inString:Boolean = false):void {
        if (value == null) {
            obj[ descProperty.name] = null;
            return;
        }
        var aoc:IAutomationObject = ( relativeParent != null ) ? relativeParent : obj as IAutomationObject;
        var part:AutomationIDPart = new AutomationIDPart();

        var str:String = value as String;
        var items:Array = new Array();
        if( str.indexOf(":=") > -1 ){
        	items = str.split(":=");
        }

        if (items.length == 2) {
            part[ items[ 0 ] ] = items[ 1 ];
        }
        else {
            part.automationName = str;
        }

        var arr:Array = Automation.automationManager.resolveIDPart(aoc, part);
        obj[ descProperty.name ] = arr[ 0 ];

//todo: tell when debugging.
//	    	if (ao.length > 1)
//	    	{
//	    		trace("Multiple matches found");
//	    	}

    }
}
}